Basic Tensorflow


In [1]:
import numpy as np
import tensorflow as tf
print ("Packages are loaded!!!")


Packages are loaded!!!

Session


In [3]:
sess = tf.Session()
print ("Open Session")


Open Session

Tensorflow Constant


In [4]:
def print_tf(x):
    print ("TYPE IS\n %s" % (type(x)))
    print ("VALUE IS\n %s" % (x))
hello = tf.constant("Hello Tensorflow!!!")
print_tf(hello)


TYPE IS
 <class 'tensorflow.python.framework.ops.Tensor'>
VALUE IS
 Tensor("Const:0", shape=(), dtype=string)

Constant after Session.run()


In [5]:
hello_out = sess.run(hello)
print_tf(hello_out)


TYPE IS
 <class 'bytes'>
VALUE IS
 b'Hello Tensorflow!!!'

Other types of Constant


In [6]:
a = tf.constant(1.5)
b = tf.constant(2.5)
print_tf(a)
print_tf(b)


TYPE IS
 <class 'tensorflow.python.framework.ops.Tensor'>
VALUE IS
 Tensor("Const_1:0", shape=(), dtype=float32)
TYPE IS
 <class 'tensorflow.python.framework.ops.Tensor'>
VALUE IS
 Tensor("Const_2:0", shape=(), dtype=float32)

In [7]:
a_out = sess.run(a)
b_out = sess.run(b)
print_tf(a_out)
print_tf(b_out)


TYPE IS
 <class 'numpy.float32'>
VALUE IS
 1.5
TYPE IS
 <class 'numpy.float32'>
VALUE IS
 2.5

Operators


In [8]:
a_plus_b = tf.add(a, b)
print_tf(a_plus_b)


TYPE IS
 <class 'tensorflow.python.framework.ops.Tensor'>
VALUE IS
 Tensor("Add:0", shape=(), dtype=float32)

In [9]:
a_plus_b_out = sess.run(a_plus_b)
print_tf(a_plus_b_out)


TYPE IS
 <class 'numpy.float32'>
VALUE IS
 4.0

In [10]:
a_mul_b = tf.mul(a, b)
print_tf(a_mul_b)


TYPE IS
 <class 'tensorflow.python.framework.ops.Tensor'>
VALUE IS
 Tensor("Mul:0", shape=(), dtype=float32)

In [11]:
a_mul_b_out = sess.run(a_mul_b)
print_tf(a_mul_b_out)


TYPE IS
 <class 'numpy.float32'>
VALUE IS
 3.75

Variables


In [12]:
weight = tf.Variable(tf.random_normal([5, 2], stddev=0.1))
print_tf(weight)


TYPE IS
 <class 'tensorflow.python.ops.variables.Variable'>
VALUE IS
 <tensorflow.python.ops.variables.Variable object at 0x7fc51d704048>

In [13]:
weight_out = sess.run(weight)
print_tf(weight_out)


---------------------------------------------------------------------------
FailedPreconditionError                   Traceback (most recent call last)
/home/parksurk/.virtualenvs/cv/lib/python3.5/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
    714     try:
--> 715       return fn(*args)
    716     except errors.OpError as e:

/home/parksurk/.virtualenvs/cv/lib/python3.5/site-packages/tensorflow/python/client/session.py in _run_fn(session, feed_dict, fetch_list, target_list, options, run_metadata)
    696                                  feed_dict, fetch_list, target_list,
--> 697                                  status, run_metadata)
    698 

/usr/lib/python3.5/contextlib.py in __exit__(self, type, value, traceback)
     65             try:
---> 66                 next(self.gen)
     67             except StopIteration:

/home/parksurk/.virtualenvs/cv/lib/python3.5/site-packages/tensorflow/python/framework/errors.py in raise_exception_on_not_ok_status()
    449           compat.as_text(pywrap_tensorflow.TF_Message(status)),
--> 450           pywrap_tensorflow.TF_GetCode(status))
    451   finally:

FailedPreconditionError: Attempting to use uninitialized value Variable
	 [[Node: _send_Variable_0 = _Send[T=DT_FLOAT, client_terminated=true, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/cpu:0", send_device_incarnation=-5316005961847165296, tensor_name="Variable:0", _device="/job:localhost/replica:0/task:0/cpu:0"](Variable)]]

During handling of the above exception, another exception occurred:

FailedPreconditionError                   Traceback (most recent call last)
<ipython-input-13-e453db2b7ada> in <module>()
----> 1 weight_out = sess.run(weight)
      2 print_tf(weight_out)

/home/parksurk/.virtualenvs/cv/lib/python3.5/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
    370     try:
    371       result = self._run(None, fetches, feed_dict, options_ptr,
--> 372                          run_metadata_ptr)
    373       if run_metadata:
    374         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

/home/parksurk/.virtualenvs/cv/lib/python3.5/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
    634     try:
    635       results = self._do_run(handle, target_list, unique_fetches,
--> 636                              feed_dict_string, options, run_metadata)
    637     finally:
    638       # The movers are no longer used. Delete them.

/home/parksurk/.virtualenvs/cv/lib/python3.5/site-packages/tensorflow/python/client/session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
    706     if handle is None:
    707       return self._do_call(_run_fn, self._session, feed_dict, fetch_list,
--> 708                            target_list, options, run_metadata)
    709     else:
    710       return self._do_call(_prun_fn, self._session, handle, feed_dict,

/home/parksurk/.virtualenvs/cv/lib/python3.5/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
    726         except KeyError:
    727           pass
--> 728       raise type(e)(node_def, op, message)
    729 
    730   def _extend_graph(self):

FailedPreconditionError: Attempting to use uninitialized value Variable
	 [[Node: _send_Variable_0 = _Send[T=DT_FLOAT, client_terminated=true, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/cpu:0", send_device_incarnation=-5316005961847165296, tensor_name="Variable:0", _device="/job:localhost/replica:0/task:0/cpu:0"](Variable)]]

Why does this error occur?


In [14]:
init = tf.initialize_all_variables()
sess.run(init)
print ("Initializing all variables")


Initializing all variables

Once, we initialize variables


In [15]:
weight_out = sess.run(weight)
print_tf(weight_out)


TYPE IS
 <class 'numpy.ndarray'>
VALUE IS
 [[ 0.01749201  0.05604374]
 [-0.02584599 -0.01342603]
 [ 0.00850607  0.09707528]
 [ 0.05021013  0.02345535]
 [-0.07496618  0.04391197]]

Placeholders


In [16]:
x = tf.placeholder(tf.float32, [None, 5])
print_tf(x)


TYPE IS
 <class 'tensorflow.python.framework.ops.Tensor'>
VALUE IS
 Tensor("Placeholder:0", shape=(?, 5), dtype=float32)

Operation with Variables and Placeholders


In [17]:
oper = tf.matmul(x, weight)
print_tf(oper)


TYPE IS
 <class 'tensorflow.python.framework.ops.Tensor'>
VALUE IS
 Tensor("MatMul:0", shape=(?, 2), dtype=float32)

In [18]:
data = np.random.rand(1, 5)
oper_out = sess.run(oper, feed_dict={x: data})
print_tf(oper_out)


TYPE IS
 <class 'numpy.ndarray'>
VALUE IS
 [[ 0.01761598  0.0902454 ]]

In [19]:
data = np.random.rand(2, 5)
oper_out = sess.run(oper, feed_dict={x: data})
print_tf(oper_out)


TYPE IS
 <class 'numpy.ndarray'>
VALUE IS
 [[ 0.01181585  0.1606355 ]
 [-0.01020296  0.0454668 ]]

In [ ]: